package 栈;

import java.util.Stack;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/5/4 19:54
 * @Description:
 */
public class 接雨水 {

    public static int trap(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }

        Stack<Integer> stack = new Stack<>();
        int area = 0;

        for (int i = 0; i < height.length; i++) {
            while (!stack.isEmpty() && height[i] > height[stack.peek()] ){
                Integer pop = stack.pop();
                if(stack.isEmpty()){
                    break;
                }
                int width = i - stack.peek() - 1;
                int a = Math.min(height[i], height[stack.peek()]) - height[pop];
                area = area + (a * width);
            }
            stack.push(i);
        }
        return area;
    }

    public static void main(String[] args) {
        int[] height = {2, 1, 3};
        int trappedWater = trap(height);
        System.out.println("Trapped water: " + trappedWater); // 输出: Trapped water: 6
    }

}
